package com.software.levelupandroid.home.ui.home;

import android.annotation.SuppressLint;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.RelativeLayout;

import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AlertDialog;
import androidx.core.content.ContextCompat;
import androidx.fragment.app.Fragment;
import androidx.lifecycle.Observer;
import androidx.lifecycle.ViewModelProvider;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.google.gson.Gson;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.listener.OnLoadMoreListener;
import com.scwang.smartrefresh.layout.listener.OnRefreshListener;
import com.software.levelupandroid.R;
import com.software.levelupandroid.entity.Resource;
import com.software.levelupandroid.entity.Result;
import com.software.levelupandroid.entity.Task;
import com.software.levelupandroid.entity.User;
import com.software.levelupandroid.home.adapter.TaskItemAdapter;
import com.software.levelupandroid.home.adapter.ToDoItemAdapter;
import com.software.levelupandroid.systemTask.view.activity.FirstSelectionActivity;
import com.software.levelupandroid.taskShow.TaskShowActivity;
import com.software.levelupandroid.utils.ToastUtil;
import com.software.levelupandroid.utils.UserUtil;

import java.util.ArrayList;
import java.util.List;

public class HomeFragment extends Fragment {
    private RecyclerView recyclerView;
    private RecyclerView recyclerViewToDo;
    private TaskItemAdapter taskItemAdapter;
    private ToDoItemAdapter toDoTaskAdapter;
    private RelativeLayout rlHomeSystemCard;
    private RelativeLayout rlHomeFinishCard;
    private RelativeLayout rlHomeFailureCard;
    private RelativeLayout rlHomeOnGoingCard;
    private RelativeLayout rlCollapse;
    private RelativeLayout rlCollapseToDo;
    private SmartRefreshLayout srlHome;
    private HomeViewModel homeViewModel;
    private TextView tvTodayTaskSize;
    private TextView tvToDoSize;
    private ImageButton ibHomeShowTodayTask;
    private ImageButton ibHomeShowToDo;
    private List<Task> taskList = new ArrayList<>();
    private boolean isCollapse = false, isCollapseToDo = true;

    public View onCreateView(@NonNull LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_home, container, false);

        initView(view);
        initViewModel();
//        getData();

        manageRecycler();

        observeLiveData();
        setListener();

        return view;
    }

    @Override
    public void onResume() {
        super.onResume();
        homeViewModel.getAllTasksByDate(getActivity());
        homeViewModel.getAllToDoTasks(getActivity());
    }

    /**
     * 设置控件的监听器
     */
    private void setListener() {
        rlHomeSystemCard.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Intent intent = new Intent(getActivity(), FirstSelectionActivity.class);
                startActivity(intent);
            }
        });

        rlHomeOnGoingCard.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Intent intent = new Intent(getActivity(), TaskShowActivity.class);
                intent.putExtra("status", 0);
                startActivity(intent);
            }
        });

        rlHomeFailureCard.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Intent intent = new Intent(getActivity(), TaskShowActivity.class);
                intent.putExtra("status", -1);
                startActivity(intent);
            }
        });

        rlHomeFinishCard.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Intent intent = new Intent(getActivity(), TaskShowActivity.class);
                intent.putExtra("status", 1);
                startActivity(intent);
            }
        });

        rlCollapse.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (isCollapse){
                    isCollapse = false;
                    Drawable expand = ContextCompat.getDrawable(getContext(), R.drawable.baseline_keyboard_arrow_down_24);
                    ibHomeShowTodayTask.setImageDrawable(expand);
                    recyclerView.setVisibility(View.VISIBLE);
                }else {
                    isCollapse = true;
                    Drawable collapse = ContextCompat.getDrawable(getContext(), R.drawable.baseline_keyboard_arrow_right_black_24);
                    ibHomeShowTodayTask.setImageDrawable(collapse);
                    recyclerView.setVisibility(View.GONE);
                }
            }
        });

        rlCollapseToDo.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (isCollapseToDo){
                    isCollapseToDo = false;
                    Drawable expand = ContextCompat.getDrawable(getContext(), R.drawable.baseline_keyboard_arrow_down_24);
                    ibHomeShowToDo.setImageDrawable(expand);
                    recyclerViewToDo.setVisibility(View.VISIBLE);
                }else {
                    isCollapseToDo = true;
                    Drawable collapse = ContextCompat.getDrawable(getContext(), R.drawable.baseline_keyboard_arrow_right_black_24);
                    ibHomeShowToDo.setImageDrawable(collapse);
                    recyclerViewToDo.setVisibility(View.GONE);
                }
            }
        });

        //下拉刷新
//        srlHome.setOnRefreshListener(new OnRefreshListener() {
//            @Override
//            public void onRefresh(@NonNull RefreshLayout refreshLayout) {
//                homeViewModel.updateTaskListInfo(getActivity());
//                refreshLayout.setReboundDuration(2000);
//                refreshLayout.finishRefresh();
//            }
//        });

        //上拉加载
//        srlHome.setOnLoadMoreListener(new OnLoadMoreListener() {
//            @Override
//            public void onLoadMore(@NonNull RefreshLayout refreshLayout) {
//                homeViewModel.getTaskListInfo(getActivity());
//                refreshLayout.setReboundDuration(2000);
//                refreshLayout.finishLoadMore();
//            }
//        });
    }

    /**
     * 管理recyclerView
     */
    private void manageRecycler() {
        taskItemAdapter = new TaskItemAdapter(getActivity(), homeViewModel);
        toDoTaskAdapter = new ToDoItemAdapter(getActivity(), homeViewModel);

        recyclerView.setLayoutManager(new LinearLayoutManager(this.getContext()));
        recyclerViewToDo.setLayoutManager(new LinearLayoutManager(this.getContext()));
        recyclerView.setAdapter(taskItemAdapter);
        recyclerViewToDo.setAdapter(toDoTaskAdapter);
    }

    /**
     * 实例化ViewModel实例
     */
    private void initViewModel() {
        ViewModelProvider viewModelProvider = new ViewModelProvider(this);
        homeViewModel = viewModelProvider.get(HomeViewModel.class);
    }

    /**
     * 调用ViewModel的接口从服务端获取数据
     */
    private void getData() {
        homeViewModel.getAllTasksByDate(getActivity());
        homeViewModel.getAllToDoTasks(getActivity());
    }

    /**
     * 观察LiveData对象
     */
    private void observeLiveData() {
//        homeViewModel.getTaskListLiveData().observe(this, new Observer<List<Task>>() {
//            @Override
//            public void onChanged(List<Task> tasks) {
//                if (tasks == null) {
//                    Toast.makeText(getContext(), "获取tasks失败", Toast.LENGTH_SHORT).show();
//                    return;
//                }
////                if (tasks.size() % 10 != 0) {
////                    srlHome.finishLoadMoreWithNoMoreData();
////                }
//                taskItemAdapter.updateTaskList(tasks);
//            }
//        });

        //观察有开始时间任务列表的LiveData
        homeViewModel.getTaskListLiveData().observe(this, new Observer<Resource<List<Task>>>() {
            @Override
            public void onChanged(Resource<List<Task>> listResource) {
                if (listResource != null){
                    if (listResource.isSuccess()){
                        taskItemAdapter.updateTaskList(listResource.getData());
                        tvTodayTaskSize.setText(listResource.getData().size() + "");
                    }else if (listResource.isFailure()){
                        ToastUtil.showToastOnUI(getActivity(), listResource.getErrorMessage());
                    } else if (listResource.isLoading()) {

                    }
                }
            }
        });

        //观察待办的任务列表的LiveData
        homeViewModel.getToDoTaskListLiveData().observe(this, new Observer<Resource<List<Task>>>() {
            @Override
            public void onChanged(Resource<List<Task>> listResource) {
                if (listResource != null){
                    if (listResource.isSuccess()){
                        toDoTaskAdapter.updateTaskList(listResource.getData());
                        tvToDoSize.setText(listResource.getData().size() + "");
                    }else if (listResource.isFailure()){
                        ToastUtil.showToastOnUI(getActivity(), listResource.getErrorMessage());
                    } else if (listResource.isLoading()) {

                    }
                }
            }
        });

        //观察任务完成时经验值的LiveData
        homeViewModel.getIsUpdateLiveData().observe(this, new Observer<Resource<Result>>() {
            @Override
            public void onChanged(Resource<Result> resultResource) {
                if (resultResource != null){
                    if (resultResource.isSuccess()){
                        Result<User> data = resultResource.getData();
                        System.out.println(data);
                        if (data.getCode().equals("200")){
                            User user = data.getData();
                            if (user != null){
                                //TODO 展示升级的通知提示框
                                AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
                                builder.setTitle("升级通知")
                                        .setMessage("恭喜达到 " + user.getGradeId() + " 级")
                                        .setCancelable(true)
                                        .setPositiveButton("确定", new DialogInterface.OnClickListener() {
                                            @Override
                                            public void onClick(DialogInterface dialogInterface, int i) {
                                                dialogInterface.dismiss();
                                            }
                                        });
                                AlertDialog alertDialog = builder.create();
                                alertDialog.show();
//                                ToastUtil.showToastOnUI(getActivity(), "恭喜达到 " + user.getGradeId() + " 级");
                            }

                            UserUtil.saveUser(user, getActivity());
                        } else if (data.getCode().equals("201")) {
                            //未达到升级条件
                        } else if (data.getCode().equals("500")) {

                        }
                    }else if (resultResource.isFailure()){
                        ToastUtil.showToastOnUI(getActivity(), resultResource.getErrorMessage());
                    } else if (resultResource.isLoading()) {

                    }
                }
            }
        });
    }

    /**
     * 控件绑定
     * @param view
     */
    private void initView(View view) {
        recyclerView = view.findViewById(R.id.recyclerview_todayTask);
        recyclerViewToDo = view.findViewById(R.id.rv_toDo);
        rlHomeSystemCard = view.findViewById(R.id.rl_home_systemCard);
        rlHomeFinishCard = view.findViewById(R.id.rl_home_finishCard);
        rlHomeFailureCard = view.findViewById(R.id.rl_home_failureCard);
        rlHomeOnGoingCard = view.findViewById(R.id.rl_home_onGoingCard);
        rlCollapse = view.findViewById(R.id.rl_collapse_todayTask);
        rlCollapseToDo = view.findViewById(R.id.rl_collapse_toDo);
//        srlHome = view.findViewById(R.id.srl_home_todayTask);
        tvTodayTaskSize = view.findViewById(R.id.tv_todayTask_size);
        tvToDoSize = view.findViewById(R.id.tv_toDo_size);
        ibHomeShowTodayTask = view.findViewById(R.id.ib_home_show_todayTask);
        ibHomeShowToDo = view.findViewById(R.id.ib_home_show_toDo);
    }

    /**
     * 数据初始化
     */
    @SuppressLint("NewApi")
    private void initData() {
        taskList = new ArrayList<>();
        Task task1 = new Task();
        task1.setTaskId(1);
        task1.setTaskTitle("背单词");
        task1.setStartTime("2024-5-1 9:00");
        task1.setEndTime("2024-5-1 12:00");
        task1.setTaskType(2);
        task1.setPriority(3);
        task1.setStatus(1);
        taskList.add(task1);

        Task task2 = new Task();
        task2.setTaskId(2);
        task2.setTaskTitle("写作业");
        task2.setStartTime("2024-5-1 13:00");
        task2.setEndTime("2024-5-1 13:30");
        task2.setTaskType(2);
        task2.setPriority(3);
        task2.setStatus(-1);
        taskList.add(task2);

        Task task3 = new Task();
        task3.setTaskId(3);
        task3.setTaskTitle("吃饭");
        task3.setStartTime("2024-5-1 14:00");
        task3.setEndTime(null);
        task3.setTaskType(1);
        task3.setPriority(0);
        task3.setStatus(0);
        taskList.add(task3);

        Task task4 = new Task();
        task4.setTaskId(4);
        task4.setTaskTitle("锻炼");
        task4.setStartTime("2024-5-1 21:00");
        task4.setEndTime("2024-5-1 21:30");
        task4.setTaskType(1);
        task4.setPriority(1);
        task4.setStatus(0);
        taskList.add(task4);

        Task task5 = new Task();
        task5.setTaskId(5);
        task5.setTaskTitle("吃饭");
        task5.setStartTime("2024-5-1 12:00");
        task5.setEndTime(null);
        task5.setTaskType(0);
        task5.setPriority(0);
        task5.setStatus(0);
        taskList.add(task5);

        Task task6 = new Task();
        task6.setTaskId(6);
        task6.setTaskTitle("锻炼");
        task6.setStartTime("2024-5-1 21:00");
        task6.setEndTime("2024-5-1 21:00");
        task6.setTaskType(1);
        task6.setPriority(1);
        task6.setStatus(0);
        taskList.add(task6);

    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        homeViewModel.getTaskListLiveData().removeObservers(this);
        homeViewModel.getToDoTaskListLiveData().removeObservers(this);
    }
}